package model;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Branch;
import org.dom4j.Element;

public class ClassMapper {
	private List<Item> itemList;
	
	public ClassMapper() {
		this.itemList = new ArrayList<Item>();
	}
	
	/**
	 * Create XML element representing the inventory.
	 * 
	 * @param parent the parent XML element or document
	 * @return the Element representing the inventory
	 */
	public Element toElement(Branch parent) {
		Element inventory = parent.addElement("Inventory");
	
		// add Item elements for each Item
		for (Item item : itemList) {
			item.toElement(inventory);
		}
		
		return inventory;
	}

	/**
	 * Initialize the Inventory from given XML element or document.
	 * 
	 * @param element XML element representing the inventory
	 */
	public void fromElement(Element element) {
		// Clear out existing Items in inventory.
		itemList.clear();
		
		// Select all Item elements
		List<?> itemNodes = element.selectNodes("//Inventory/Item");
		for (Object obj : itemNodes) {
			// Create an Item, initialize it from the selected Item element, and
			// add it to the list
			Item item = new Item();
			item.fromElement((Element) obj);
			itemList.add(item);
		}
	}

	/**
	 * Add a new item to the collection.
	 * It must have a different name than any existing item.
	 * 
	 * @param item the new item to add
	 * @throws ClassMapException if there is already an Item with the same name
	 */
	public void addItem(Item item) throws ClassMapException {
		Item existingItem = getItem(item.getName());
		if (existingItem != null) {
			throw new ClassMapException("Item " + item.getName() + " already exists");
		}
		itemList.add(item);
	}

	/**
	 * Get the Item with the given name.
	 * Returns null if there is no such Item.
	 * 
	 * @param name the name of the Item to get
	 * @return the Item with the given name, or null if there is no such item
	 */
	public Item getItem(String name) {
		for (Item item : itemList) {
			if (item.getName().equals(name)) {
				return item;
			}
		}
		return null;
	}
}
